<?php

namespace app\api\controller;

use app\common\Helper;
use app\api\wxchat\WxBizDataCrypt;

use app\admin\model\User;

class UserInfo extends Base
{

    public function getUserInfo($where = '')
    {
        $param = self::getHttpParam();
        if (empty($param->appId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'appId不能为空');
        }
        if (empty($param->openId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'openId不能为空');
        }

        $appId = $param->appId;
        $openId = $param->openId;
        $user = User::where('openId', $openId)->find();

        if (empty($user)) {
            $user = new User;
            $user->id = Helper::getUUID22();
            $user->openId = $openId;
            $user->save();
        }

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $user);
    }

    /**
     * @return \think\response\Json
     * 解析手机号
     */
    public function decodePhone()
    {
        $param = self::getHttpParam();
        if (empty($param->openId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'openId不能这空');
        } else if (empty($param->appId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'appId不能这空');
        } else if (empty($param->encryptedData)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'encryptedData不能这空');
        } else if (empty($param->iv)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'iv不能这空');
        } else if (empty($param->sessionKey)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'sessionKey不能这空');
        } else {
            $appId = $param->appId;
            $openId = $param->openId;
            $encryptedData = $param->encryptedData;
            $iv = $param->iv;
            $sessionKey = $param->sessionKey;

            $pc = new WxBizDataCrypt($appId, $sessionKey);
            $errCode = $pc->decryptData($encryptedData, $iv, $data);

            if ($errCode == 0) {
                $phone['mobile'] = json_decode($data)->phoneNumber;
//                $user = User::where('openId', $openId)->find();
//                $user->phone = json_decode($data)->phoneNumber;
//                $user->save();

                return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $phone);
            } else {
                return show(config('status.ERROR_STATUS'), $errCode, '手机号解析错误');
            }
        }
    }

}